package cn.meye11.crm.common;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import lombok.EqualsAndHashCode;

@Data
@EqualsAndHashCode(callSuper = true)
public class BaseException extends RuntimeException {

    private static final long serialVersionUID = -6875838312173763613L;

    // 202 是http状态码 服务器已接受请求，但尚未处理。
    private int httpCode = 202;
    private String[] errors;

    public BaseException(String errorMsg, Number errorCode) {
        super(createFriendlyErrMsg(errorMsg, errorCode));
    }

    public BaseException(String errorMsg) {
        super(errorMsg);
    }

    public BaseException(String errorMsg, String[] errors) {
        super(errorMsg);
        this.errors = errors;
    }

    private static String createFriendlyErrMsg(String msgBody, Number errorCode) {
        RestResponse<String> returnMessage = RestResponse.failed( msgBody);
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(returnMessage);
        } catch (JsonProcessingException e) {
            Meiye11ExceptionUtils.error(e, msgBody, String.valueOf(errorCode));
        }
        return "BaseException error";
    }
}
